//
//  YSChatViewController.m
//  YSEmoticonKeyboard
//
//  Created by MOLBASE on 2017/12/20.
//  Copyright © 2017年 YangShen. All rights reserved.
//

#import "YSChatViewController.h"
#import "YSChatMessageFrame.h"
#import "YSMessageDataBase.h"
#import "YSChatMessageCell.h"
#import "YSEmoticonTopBar.h"
#import "UIView+YSAdd.h"
#import "Masonry.h"

static CGFloat const kChatToolsViewHeight = 40;


@interface YSChatViewController () <UITableViewDelegate, UITableViewDataSource, YSTopBarDelegate>

@property (nonatomic, strong) YSEmoticonTopBar *chatTopBar;
@property (nonatomic, strong) UITableView *chatTableView;
@property (nonatomic, strong) NSMutableArray *dataSource;

@end

@implementation YSChatViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"奔波儿灞与霸波儿奔";
    
    [self setupUI];
    [self prepareData];
}

#pragma mark - setupUI
- (void)setupUI {
    self.view.backgroundColor = YSEmoticonRGB(250, 250, 250);
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    [self.view addSubview:self.chatTableView];
    [self.view addSubview:self.chatTopBar];
}

#pragma mark - prepareData
- (void)prepareData {
    self.dataSource = @[].mutableCopy;
    
    NSArray *messages = @[@"听说现在可以在网上用身份证查到开房记录了！", @"啊？天呐，那多难为情啊！！[惊恐]", @"[奸笑]怕了吧", @"如果被人发现我从来没开过房，那多没面子啊[流泪]"];
    
    for (int i = 0; i < messages.count; i++) {
        YSChatMessageFrame *cellFrame = [[YSChatMessageFrame alloc] init];
        YSChatMessage *message = [[YSChatMessage alloc] init];
        message.messageContent = messages[i];
        
        [self.dataSource addObject:cellFrame];
        if (i % 2 == 0) {
            message.userType = YSUserTypeMe;
            message.userId = 99;
        } else {
            message.userType = YSUserTypeOther;
            message.userId = 0;
        }
        
        cellFrame.chatMessage = message;
    }
    
    NSMutableArray *messageArray = [YSMessageDataBase queryData:nil];
    [messageArray enumerateObjectsUsingBlock:^(YSChatMessage *message, NSUInteger idx, BOOL * _Nonnull stop) {
        YSChatMessageFrame *cellFrame = [[YSChatMessageFrame alloc]init];
        cellFrame.chatMessage = message;
        [self.dataSource addObject:cellFrame];
    }];
    [self.chatTableView reloadData];
    
    [self scrollTableViewToBottom];
}

#pragma mark - private method
// 滚动到底部
- (void)scrollTableViewToBottom {
    if (self.dataSource.count > 0) {
        NSLog(@"scrollTableViewToBottom");
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:self.dataSource.count - 1 inSection:0];
        [self.chatTableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionBottom animated:NO];
    }
}

#pragma mark - event response
- (void)tapTableView:(UITapGestureRecognizer *)tapGest {
    [self.view endEditing:YES];
    
    UIMenuController *menuController = [UIMenuController sharedMenuController];
    if (menuController.menuVisible) {
        [menuController setMenuVisible:NO animated:NO];
    }
}

#pragma mark - UITableViewDelegate, UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    YSChatMessageCell *cell = [YSChatMessageCell cellWithTableView:self.chatTableView];
    cell.tag = indexPath.row;
    cell.messageFrame = self.dataSource[indexPath.row];
    
    __weak typeof(self) weakSelf = self;
    cell.deleteMessage = ^(YSChatMessageFrame *messageFrame) {
        NSUInteger index = [self.dataSource indexOfObject:messageFrame];
        [weakSelf.dataSource removeObject:messageFrame];
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:index inSection:0];
        [weakSelf.chatTableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
    };
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    YSChatMessageFrame *cellFrame = self.dataSource [indexPath.row];
    return cellFrame.cellHeight;
}

#pragma mark - YSTopBarDelegate
- (void)emoticonTopBar:(YSEmoticonTopBar *)topBar sendMessage:(NSString *)message {
    NSLog(@"%@", message);
    
    //点击发送，发出一条消息
    YSChatMessageFrame *cellFrame = [[YSChatMessageFrame alloc] init];
    YSChatMessage *chatMessage = [[YSChatMessage alloc] init];
    chatMessage.messageContent = message;
    chatMessage.userType = YSUserTypeMe;
    chatMessage.userId = 99;
    cellFrame.chatMessage = chatMessage;
    
    [self.dataSource addObject:cellFrame];
    [self.chatTableView reloadData];
    [self scrollTableViewToBottom];
    
    //保存到数据库
    NSString *sql = [NSString stringWithFormat:@"(userId,userName, userHeadImage, messageContent, userType) VALUES ('%zd','%@','%@', '%@', '%zd')", chatMessage.userId, chatMessage.userName, chatMessage.userHeadImage, chatMessage.messageContent, chatMessage.userType];
    [YSMessageDataBase insertMessageWithSql:sql];
}

- (void)emoticonTopBarUpdateSuperView {
    [self updateChatList];
}

// 重设tabbleview的frame并根据是否在底部来执行滚动到底部的动画（不在底部就不执行，在底部才执行）
- (void)updateChatList {
    CGFloat offSetY = self.chatTableView.contentSize.height - self.chatTableView.ys_height;
    //判断是否需要滚动到底部，给一个误差值
    if (self.chatTableView.contentOffset.y > offSetY - 5 || self.chatTableView.contentOffset.y > offSetY + 5) {
        self.chatTableView.ys_height = self.chatTopBar.ys_y - 64;
        [self scrollTableViewToBottom];
    }else {
        self.chatTableView.ys_height = self.chatTopBar.ys_y - 64;
    }
}

#pragma mark - 懒加载
- (UITableView *)chatTableView {
    if (!_chatTableView) {
        _chatTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 64, self.view.bounds.size.width, self.view.bounds.size.height - 64 - kChatToolsViewHeight) style:UITableViewStylePlain];
        _chatTableView.backgroundColor = YSEmoticonRGB(236, 237, 241);
        _chatTableView.tableFooterView = [UIView new];
        _chatTableView.dataSource = self;
        _chatTableView.delegate = self;
        _chatTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapTableView:)];
        [_chatTableView addGestureRecognizer:tap];
    }
    return _chatTableView;
}

- (YSEmoticonTopBar *)chatTopBar {
    if (!_chatTopBar) {
        _chatTopBar = [[YSEmoticonTopBar alloc] init];
        _chatTopBar.delegate = self;
        _chatTopBar.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    }
    return _chatTopBar;
}

@end
